package cn.zcscloud.mall.controller;

import cn.zcscloud.mall.common.PageRequest;
import cn.zcscloud.mall.common.R;
import cn.zcscloud.mall.mbg.model.UmsResource;
import cn.zcscloud.mall.service.UmsResourceService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/resource")
@CrossOrigin
public class UmsResourceController {

    @Autowired
    private UmsResourceService umsResourceService;

    /**
     * 查询所有后台资源
     *
     * @return
     */
    @GetMapping("/listAll")
    public R<List<UmsResource>> listAll() {
        List<UmsResource> list = umsResourceService.list();
        return R.success(list);
    }

    /**
     * 添加后台资源
     *
     * @param umsResource
     * @return
     */
    @PostMapping("/create")
    public R<String> create(@RequestBody UmsResource umsResource) {
        umsResourceService.save(umsResource);
        return R.success(null);
    }

    /**
     * 根据ID删除后台资源
     *
     * @param id
     * @return
     */
    @PostMapping("/delete/{id}")
    public R<String> delete(@PathVariable("id") Integer id) {
        umsResourceService.deleteById(id);
        return R.success(null);
    }

    /**
     * 修改后台资源
     *
     * @param umsResource
     * @param id
     * @return
     */
    @PostMapping("/update/{id}")
    public R<String> update(@RequestBody UmsResource umsResource, @PathVariable("id") Integer id) {
        umsResource.setId(id.longValue());
        umsResourceService.updateById(umsResource);
        return R.success(null);
    }

    /**
     * 根据ID获取资源详情
     *
     * @return
     */
    @GetMapping("/{id}")
    public R<UmsResource> findById(@PathVariable("id") Integer id) {
        UmsResource umsResource = umsResourceService.getById(id);
        return R.success(umsResource);
    }

    /**
     * 分页模糊查询后台资源
     *
     * @return
     */
    @GetMapping("/list")
    public R<PageRequest> list(Integer categoryId, String nameKeyword, Integer pageNum, Integer pageSize, String urlKeyword) {
        //分页构造器
        IPage<UmsResource> iPage = new Page<>(pageNum, pageSize);
        //查询构造器
        LambdaQueryWrapper<UmsResource> lqw = new LambdaQueryWrapper<>();
        lqw.eq(categoryId != null, UmsResource::getCategoryId, categoryId);
        lqw.like(nameKeyword != null, UmsResource::getName, nameKeyword);
        lqw.like(urlKeyword != null, UmsResource::getUrl, urlKeyword);
        lqw.orderByDesc(UmsResource::getCreateTime);
        //查询构造并返回
        umsResourceService.page(iPage, lqw);
        PageRequest pr = PageRequest.init(iPage);
        return R.success(pr);
    }
}
